/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.process.event.internal;

import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.engine.HistoryService;
import com.je.bpm.engine.history.HistoricTaskInstance;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.model.process.events.ProcessCompletedEvent;
import com.je.bpm.runtime.process.event.listener.ProcessRuntimeEventListener;
import com.je.bpm.runtime.shared.operator.AudflagEnum;

import java.util.List;
import java.util.Map;

public class ProcessEndEventListener implements ProcessRuntimeEventListener<ProcessCompletedEvent> {

    private HistoryService historyService;
    private static final String PROCESS_VOID = "void";

    public ProcessEndEventListener(HistoryService historyService) {
        this.historyService = historyService;
    }

    @Override
    public void onEvent(ProcessCompletedEvent event) {

        CommandContext commandContext = Context.getCommandContext();
        if (null == commandContext) {
            return;
        }

        String processType = String.valueOf(commandContext.getAttribute("processType"));
        if (PROCESS_VOID.equals(processType)) {
            return;
        }

        //执行自定义事件
        String pdId = event.getEntity().getProcessDefinitionId();
        //获取bpmnModel
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(pdId);
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(event.getProcessInstanceId())
                .orderByHistoricTaskInstanceStartTime().desc().list();

        String taskId = "";
        String taskName = "";
        String taskDefinitionKey = "";
        String taskBusinessKey = event.getEntity().getBusinessKey();
        if (list != null && list.size() > 0) {
            taskId = list.get(0).getId();
            taskDefinitionKey = list.get(0).getTaskDefinitionKey();
            taskName = list.get(0).getName();
        }
        Object submitCommentObj = commandContext.getAttribute(CommandContext.SUBMIT_COMMENT);
        String comment = "";
        if (submitCommentObj != null) {
            comment = String.valueOf(submitCommentObj);
        }
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().invokeEvent
                (bpmnModel.getMainProcess().getCustomEventListeners(), taskName,
                        taskDefinitionKey, "",
                        CustomEvent.CustomEventEnum.PROCESS_END, commandContext, comment, taskId, OperatorEnum.TASK_SUBMIT_OPERATOR);

        Map<String, Object> bean = commandContext.getBean();
        bean.put("SY_AUDFLAG", AudflagEnum.ENDED.toString());
        commandContext.updateBean(bean, taskBusinessKey, bpmnModel.getMainProcess().getProcessConfig());

    }

}